import { useDiscreteApi } from '@/composables'
import {  toRefsPreferencesStore } from '@/stores'

import type { Router } from 'vue-router'
const routeList = [
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home.vue'),
  }
]
const Layout = () => import('@/layout/index.vue')

const { loadingBar } = useDiscreteApi()

const { showTopLoadingBar } = toRefsPreferencesStore()


export function setupRouterGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (showTopLoadingBar.value) {
      loadingBar.start()
    }

    // if (to.name === 'home') {
    //   if (!token.value) {
    //     next()
    //   } else {
    //     next(from.fullPath)
    //   }

    //   return false
    // }

    // if (!token.value) {
    //   cleanup()
    //   next()
    //   return false
    // }
    console.log('router', router,router.hasRoute('layout'))
    if ( !router.hasRoute('layout')) {
      try {
        router.addRoute({
          path: '/',
          name: 'layout',
          component: Layout,
          // if you need to have a redirect when accessing / routing
          redirect: '/dashboard',
          children: routeList,
        })

        next(to.fullPath)
      } catch (error) {
        console.error('Error resolving user menu or adding route:', error)
        next()
      }

      return false
    }

    next()
    return false
  })

  router.beforeResolve((_, __, next) => {
    next()
  })

  router.afterEach(() => {
    if (showTopLoadingBar.value) {
      loadingBar.finish()
    }
  })
}
